package com.qf.fmall2204.config;

import com.qf.fmall2204.constants.Constants;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){

        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();

        // 白名单
        chainDefinition.addPathDefinition("/user/login","anon");
        chainDefinition.addPathDefinition("/user/regist","anon");

        chainDefinition.addPathDefinition("/error","anon");

        chainDefinition.addPathDefinition("/index/category-recommends","jwt");
        chainDefinition.addPathDefinition("/index/indeximg","jwt");


        return chainDefinition;

    }


    @Bean
    public Realm customRealm(){

        CustomRealm customRealm = new CustomRealm();

        // 设置密码匹配器对象
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(Constants.HASH_TIMES);

        customRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        return customRealm;

    }

    @Bean
    public Realm jwtRealm(){
        JwtRealm jwtRealm = new JwtRealm();

        jwtRealm.setCredentialsMatcher(new CredentialsMatcher() {
            @Override
            public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
                return true;
            }
        });

        return jwtRealm;
    }

}
